import React, { useEffect, useState } from 'react'
import { NavBar, Toast, Form, Button, Input, Address, Cell, Switch } from '@nutui/nutui-react'
import { ArrowLeft } from '@nutui/icons-react'
import { useLocation, useNavigate } from 'react-router-dom'
import axios from 'axios'
import city from "../../../City.js"
//添加收货地址
export default function Addharvest() {
    let cateId = useLocation().search.split('=')[1]

    // 获取用户id
    let userId = localStorage.getItem("userId")
    let navigate = useNavigate()
    // 收货人
    let [name, setname] = useState("")
    // 手机号
    let [phone, setphone] = useState("")
    // 选择省市县
    const [text, setText] = useState('选择地址')
    // 详细地址
    let [address, setaddress] = useState("")
    // 是否为默认地址
    let [isdefault, setisdefault] = useState(false)
    const [optionsDemo1] = useState(city)
    // 是否展示选择地址模块
    const [visible, setVisible] = useState(false)
    // 改变默认地址开关状态
    const onChangeAsync = (value, event) => {
        setTimeout(() => {
            setisdefault(value)
        }, 500)
    }
    let getupaddress = async () => {
        if (cateId) {
            let date = await axios.get(`http://127.0.0.1:3000/users/upaddress?ids=${cateId}`)
            if (date.data.code == 200) {
                let list = date.data.data
                let dz = list.address.split(' ')
                setname(list.name)
                setphone(list.phone)
                setText(dz[0])
                setaddress(dz[1])
                setisdefault(list.isdefault)
            }
        }
    }
    // 添加收货地址或修改地址
    let addHarvest = async () => {
        let names = text + " " + address//组合省市县和详细地址
        let data = await axios.get(`https://restapi.amap.com/v3/geocode/geo?address=${names}&output=JSON&key=161de523a2a2cd80ed9823b3f7e25104`)//通过地址获取经纬度
        
        // let htmlss = data.data
        // let addressname = htmlss.split("<location>")[1].split("</location>")[0].split(',')
        let addressname = data.data.geocodes[0].location.split(',')
        if (cateId) {
            let up_ress = await axios.put(`http://127.0.0.1:3000/users/upress?ids=${cateId}&userId=${userId}`, { name: name, phone: phone, address: names, isdefault: isdefault, latlong: addressname })
            if (up_ress.data.code == 200) {
                console.log("修改成功");
                navigate(-1)
            }
        }
        else {
            let add_ress = await axios.post(`http://127.0.0.1:3000/users/address?userId=${userId}`, { name: name, phone: phone, address: names, isdefault: isdefault, latlong: addressname })
            if (add_ress.data.code == 200) {
                console.log("添加成功");
                navigate(-1)
            }
        }

    }
    useEffect(() => {
        getupaddress()
    }, [])
    return (
        <div>
            {/* 导航栏 */}
            <NavBar
                back={<ArrowLeft />}
                right={
                    <>
                        <span onClick={addHarvest}>保存</span>
                    </>
                }
                onBackClick={(e) => navigate(-1)}
            >
                <span onClick={(e) => Toast.show('标题')}>{cateId ? "修改收货地址" : "新增收货地址"}</span>
            </NavBar>
            <Input
                className="nut-input-text"
                placeholder="请输入收货人"
                value={name}
                onChange={(e) => setname(e)}
            />
            <Input
                className="nut-input-text"
                placeholder="请输入手机号"
                value={phone}
                onChange={(e) => setphone(e)}
            />
            <Cell
                title="选择自定义地址"
                description={text}
                onClick={() => setVisible(true)}
            />
            <Address
                visible={visible}
                options={optionsDemo1}
                title="选择地址"
                onChange={(value) => {
                    setText(value.join(''))
                }}
                onClose={() => setVisible(false)}
            />
            <Input placeholder="请输入详细地址" value={address} onChange={(e) => { setaddress(e) }} />

            <Switch
                checked={isdefault}
                onChange={(value, event) => onChangeAsync(value, event)}
            />
            <span>是否选为默认地址</span>
            {/*
            <button onClick={() => {
                localStorage.setItem("userId", "6721e5a62c1843b123e193f9")
            }}></button>
            */}
        </div>
    )
}
